package com.atmilan.quartz.service.impl;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import com.atmilan.quartz.utils.product.ImProductUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.SyncStatusEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.dto.im.ImProductInfoSkuResDTO;
import com.atmilan.quartz.model.dto.im.ImProductPushDTO;
import com.atmilan.quartz.model.dto.im.ImProductInfoSkuResDTO.ImProductItemDTO;
import com.atmilan.quartz.model.dto.im.ImProductInfoSkuResDTO.Result;
import com.atmilan.quartz.model.dto.im.ImProductResDTO;
import com.atmilan.quartz.model.dto.im.ImProductResDTO.ImProductDTO;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.ChannelMerchant;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrValue;
import com.atmilan.quartz.model.entity.crmeb.StoreProductDescription;
import com.atmilan.quartz.model.entity.crmeb.SystemConfig;
import com.atmilan.quartz.model.entity.im.ImProduct;
import com.atmilan.quartz.model.entity.im.ImProductSku;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IChannelMerchantService;
import com.atmilan.quartz.service.IImProductService;
import com.atmilan.quartz.service.IImProductSkuService;
import com.atmilan.quartz.service.IImSyncService;
import com.atmilan.quartz.service.IMarkupRateService;
import com.atmilan.quartz.service.IStoreProductAttrService;
import com.atmilan.quartz.service.IStoreProductAttrValueService;
import com.atmilan.quartz.service.IStoreProductDescriptionService;
import com.atmilan.quartz.service.IStoreProductService;
import com.atmilan.quartz.service.ISystemConfigService;
import com.atmilan.quartz.utils.RedisUtil;
import com.atmilan.quartz.utils.source.SourceImProductUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;

/**
 * @author Howe Hsiang
 */
@Slf4j
@Service
public class ImSyncServiceImpl implements IImSyncService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ISystemConfigService systemConfigService;
    @Autowired
    IImProductService imProductService;
    @Autowired
    IImProductSkuService imProductSkuService;
    @Autowired
    IStoreProductService storeProductService;
    @Autowired
    IStoreProductAttrService storeProductAttrService;
    @Autowired
    IStoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    SourceImProductUtil sourceImProductUtil;
    @Autowired
    IChannelMerchantService channelMerchantService;
    @Autowired
    private IMarkupRateService markupRateService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    IStoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    ImProductUtil imProductUtil;

    /**
     * 获取远程数据并保存到数据源
     */
    @Override
    public Boolean syncImProduct() {
        // 数据清空
        imProductService.deleteAll();
        imProductSkuService.deleteAll();

        int pageNo = 1;
        long startId = 0;
        int pageSize = 50;
        long millis = System.currentTimeMillis();
        int index = 0;
        for(;;) {
            // 最大循环1000次
            if (index >= 1000){
                log.error("IntraMirror拉取商品数据已达最大限制");
                return false;
            }
            try {
                SystemConfig systemConfig = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                        .eq(SystemConfig :: getName, Constants.IM_TOKEN)
                        .last("LIMIT 1")
                        );
                ImProductResDTO imProductResDTO = imProductUtil.selectImPage(startId, pageSize, systemConfig);
                if(null == imProductResDTO) {
                    log.info("--------------- im获取商品接口请求失败 ---------------");
                    continue;
                }
                // 判定token失效
                if(imProductResDTO.getCode() == -1 && imProductResDTO.getError().contains("access-token")) {
                    log.info("--------------- im重新获取token ---------------");
                    imProductUtil.getImToken(systemConfig);
                    continue;
                }
                List<ImProductDTO> imProducts = imProductResDTO.getResult().getImProductDTOs();
                // 查询结束
                if(null == imProducts) {
                    return true;
                }
                // 游标移动
                pageNo++;
                startId = imProductResDTO.getResult().getCursorId();
                
                // 过滤所有可售商品数据, 查询对应sku
                //List<ImProductDTO> availableImProducts = imProducts.stream().filter(imProduct -> imProduct.getStatus() == 1).collect(Collectors.toList());
                ImProductInfoSkuResDTO imProductInfoSkuResDTO = imProductUtil.getImProductSkus(imProducts, systemConfig);
                log.info("--------------- IM远程抓取数据, 第: {} 页,  当前游标: {}, 总共: {} 条有效数据, 总耗时: {} 分  ---------------", pageNo, startId, imProducts.size(), (int)((System.currentTimeMillis() - millis) / 1000 / 60));
                if(CollectionUtils.isEmpty(imProducts)  || CollectionUtils.isEmpty(imProductInfoSkuResDTO.getResults())) {
                    continue;
                }
                // 判定token失效
                if(imProductInfoSkuResDTO.getCode() == -1 && imProductInfoSkuResDTO.getError().contains("access-token")) {
                    imProductUtil.getImToken(systemConfig);
                    continue;
                }
                // 商品保存
                List<Result> imProductItemResults = imProductInfoSkuResDTO.getResults();
                saveGoods(imProducts, imProductItemResults);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("IntraMirror拉取商品异常: ",e);
            }finally {
                index++;
            }
        }
    }
    
    /**
     * 查询增量商品
     */
    @Override
    public Boolean syncChangeTask() {
    	int pageNo = 1;
    	long startId = 1;
    	int pageSize = 50;
    	Instant instant = Instant.now();
    	long timeStampMillis = instant.toEpochMilli();
    	long fromChangedTime = timeStampMillis - (2 * 60 * 60 * 1000);
    	long millis = timeStampMillis;
    	for(;;) {
    		try {
    			SystemConfig systemConfig = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
    					.eq(SystemConfig :: getName, Constants.IM_TOKEN)
    					.last("LIMIT 1")
    					);
    			ImProductResDTO imProductResDTO = imProductUtil.selectImChangePage(startId, pageSize, systemConfig, fromChangedTime, timeStampMillis);
    			if(null == imProductResDTO) {
    				log.info("--------------- im获取商品接口请求失败 ---------------");
    				continue;
    			}
    			// 判定token失效
    			if(imProductResDTO.getCode() == -1 && imProductResDTO.getError().contains("access-token")) {
                    imProductUtil.getImToken(systemConfig);
    				continue;
    			}
    			if(null == imProductResDTO.getResult()) {
    				continue;
    			}
    			List<ImProductDTO> imProducts = imProductResDTO.getResult().getImProductDTOs();
    			// 查询结束
    			if(null == imProducts) {
    				return true;
    			}
    			// 游标移动
    			pageNo++;
    			startId = imProductResDTO.getResult().getCursorId();
    			
    			// 过滤所有可售商品数据, 查询对应sku
//    			List<ImProductDTO> availableImProducts = imProducts.stream().filter(imProduct -> imProduct.getStatus() == 1).collect(Collectors.toList());
    			log.info("--------------- IM远程抓取增量数据, 第: {} 页,  当前游标: {}, 总共: {} 条有效数据, 总耗时: {} 分  ---------------", pageNo-1, startId, imProducts.size(), (int)((System.currentTimeMillis() - millis) / 1000 / 60));
    			
    			// 商品保存
    			for(ImProductDTO productDTO : imProducts) {
    				ImProductInfoSkuResDTO imProductInfoSkuResDTO = imProductUtil.getImProductSkus(Arrays.asList(productDTO), systemConfig);
        			// 判定token失效
        			if(imProductInfoSkuResDTO.getCode() == -1 && imProductInfoSkuResDTO.getError().contains("access-token")) {
                        imProductUtil.getImToken(systemConfig);
        				continue;
        			}
        			ImProduct imProduct = new ImProduct();
					BeanUtils.copyProperties(productDTO, imProduct);
					imProduct.setImages(JSONArray.toJSONString(productDTO.getImages()));
                    String barCode = BarCodeEnum.IM.getCode() + imProduct.getProductId().toString();
                    // 空数据下架
        			if(CollectionUtils.isEmpty(imProductInfoSkuResDTO.getResults()) || CollectionUtils.isEmpty(imProductInfoSkuResDTO.getResults().get(0).getImProductItemDTOs())) {
	                	storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
	                			.eq(StoreProduct :: getBarCode, barCode)
	                			.set(StoreProduct :: getStock, 0)
	                			.set(StoreProduct :: getIsShow, 0)
	                			.set(StoreProduct :: getLastPushTime, new Date())
	                			);
        				continue;
        			}
					
					List<ImProductItemDTO> imProductItemDTO = imProductInfoSkuResDTO.getResults().get(0).getImProductItemDTOs();
					List<ImProductSku> imProductSkus = new ArrayList<>();
	                int stock = 0;
					for(ImProductItemDTO ipid : imProductItemDTO) {
						if(1 != imProductInfoSkuResDTO.getResults().get(0).getStatus() || 0 >= ipid.getQty()) {
							continue;
						}
						ImProductSku imProductSku = new ImProductSku();
						BeanUtils.copyProperties(ipid, imProductSku);
						imProductSku.setProductId(imProductInfoSkuResDTO.getResults().get(0).getProductId());
						imProductSkus.add(imProductSku);
                		stock += ipid.getQty();
					}
					
	                if(CollectionUtils.isEmpty(imProductSkus)) {
	                	storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
	                			.eq(StoreProduct :: getBarCode, barCode)
	                			.set(StoreProduct :: getStock, 0)
	                			.set(StoreProduct :: getIsShow, 0)
	                			.set(StoreProduct :: getLastPushTime, new Date())
	                			);
	                	continue;
	                }
//	                
					//构建实体
					StoreProductCrmebRequest storeProductCrmebRequest = sourceImProductUtil.buildImProduct(imProduct, imProductSkus);
					// 数据保存
					StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode(), storeProductCrmebRequest.getSuppliersId(), storeProductCrmebRequest.getKeyword());
					boolean crmebUpdate = true;
					if (null != storeProduct && null != storeProduct.getLastPushTime()) {
					    long time = (System.currentTimeMillis() - storeProduct.getLastPushTime().getTime()) / 1000 / 60;
					    if (60 > time) {
					        log.info("--------------- 该商品: {} 上次IM更新时间: {} 小于一小时, 不进行更新 ---------------", storeProductCrmebRequest.getBarCode(), storeProduct.getLastPushTime());
					        crmebUpdate = false;
					        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
					                .eq(StoreProduct::getId, storeProduct.getId())
					                .set(StoreProduct::getUpdateFlag, true)
					                );
					    }
					}
					if (crmebUpdate) {
					    storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock);
					}
    			}
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    // 商品源数据保存
    private void saveGoods(List<ImProductDTO> imProducts, List<Result> imProductItemResults) {
//        Map<Integer, Result> itemMap = imProductItemResults.stream().collect(Collectors.toMap(Result::getProductId, Function.identity(), (v1,v2) -> v2));
        // 关联sku到商品
        List<ImProductSku> imProductSkuEntity = new ArrayList<>();
        // sku数据
        for(Result imSkuResult : imProductItemResults) {
        	// 非可售商品
        	if(1 != imSkuResult.getStatus()) {
                continue;
        	}
            List<ImProductItemDTO> imProductItems = imSkuResult.getImProductItemDTOs();
            if(CollectionUtils.isEmpty(imProductItems)) {
                continue;
            }
            List<ImProductSku> imProductSku = JSON.parseArray(JSON.toJSONString(imProductItems), ImProductSku.class);
            List<ImProductSku> newSkus = new ArrayList<ImProductSku>();
            for(ImProductSku sku : imProductSku) {
                if(0 >= sku.getQty()) {
                    continue;
                }
                sku.setProductId(imSkuResult.getProductId());
                sku.setStatus(imSkuResult.getStatus());
                sku.setRetailPrice(imSkuResult.getRetailPrice());
                newSkus.add(sku);
            }
            imProductSkuEntity.addAll(newSkus);
        }
        // 商品数据
        List<com.atmilan.quartz.model.entity.im.ImProduct> imProductEntity = new ArrayList<>();
        for(ImProductDTO imProduct : imProducts) {
            Integer productId = imProduct.getProductId();
            String redisKey = "job:sync:im:" + productId;
            if (null != redisUtil.get(redisKey)) {
                log.info("--------------- 该商品: {}, 已保存, 不进行处理  ---------------", productId);
                continue;
            } else {
                redisUtil.set(redisKey, productId, 3L, TimeUnit.MINUTES);
            }
            ImProduct productEntity = new ImProduct();
            BeanUtils.copyProperties(imProduct, productEntity);
            productEntity.setImages(JSONArray.toJSONString(imProduct.getImages()));
            imProductEntity.add(productEntity);
        }
        
        imProductService.saveBatch(imProductEntity);
        imProductSkuService.saveBatch(imProductSkuEntity);
    }

    /*@PostConstruct
    public void init(){
        try {
            PageHelper.startPage(1, 10);
            List<ImProduct> imProducts = imProductService.list(Wrappers.<ImProduct>lambdaUpdate()
                     .eq(ImProduct::getProductId,9020308)
                    .eq(ImProduct::getStatus, true)
            );
            PageInfo<ImProduct> pageInfo = PageInfo.of(imProducts);
            List<ImProduct> products = pageInfo.getList();
            buildProduct(products);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getLocalizedMessage());
        }

        // 下架所有未更新数据
        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                .eq(StoreProduct::getIsEurope, ProductTypeEnum.IM.getCode())
                .eq(StoreProduct::getUpdateFlag, false)
                .eq(StoreProduct :: getIsShow, true)
                .eq(StoreProduct :: getIsDel, false)
                .set(StoreProduct::getIsShow, false)
                .set(StoreProduct::getStock, 0)
                .set(StoreProduct::getLastPushTime, new Date())
                .set(StoreProduct::getIsTusou, false)
        );
        // 下架所有sku库存
        storeProductService.downloadSku(ProductTypeEnum.IM.getCode());
    }*/

    @Override
    public Boolean pushImProduct() {
        try {
            // 当次更新少于三万条, 则不更新, 并且重新拉取
            int count = imProductService.count(Wrappers.<ImProduct>lambdaUpdate()
                    .eq(ImProduct::getStatus, true)
                    );
            if(5000 > count) {
                systemConfigService.update(Wrappers.<SystemConfig>lambdaUpdate()
                        .eq(SystemConfig :: getName, Constants.IM_SYNC_STATUS)
                        .set(SystemConfig :: getFormId, SyncStatusEnum.PUSH)
                        .set(SystemConfig :: getUpdateTime, new Date())
                        );
                log.info("--------------- IM商品源数据, 少于规定条数, 不进行下发, 总条数为: {} ---------------", count);
                return false;
            }
            
            // 将所有IM商品更新状态置为未更新
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct :: getIsEurope, ProductTypeEnum.IM.getCode())
                    .set(StoreProduct :: getUpdateFlag, false)
                    );
            
            // 商品更新操作
            int pageNo = 1;
            int pageSize = 100;
            int maxPage = (count + pageSize - 1) / pageSize;
            log.info("--------------- 开始分页查询IM商品源数据, 本次更新总条数为: {} ---------------", count);

            long millis = System.currentTimeMillis();
            while (pageNo <= maxPage) {
                try {
                    PageHelper.startPage(pageNo, pageSize);
                    List<ImProduct> imProducts = imProductService.list(Wrappers.<ImProduct>lambdaUpdate()
                            .eq(ImProduct::getStatus, true)
                            );
                    PageInfo<ImProduct> pageInfo = PageInfo.of(imProducts);
                    List<ImProduct> products = pageInfo.getList();
                    buildProduct(products);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error(e.getLocalizedMessage());
                }

                log.info("--------------- IM下发商品到数据库, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int)((System.currentTimeMillis() - millis) / 1000 / 60));
                pageNo++;
            }
            // 图搜删除
            storeProductService.delSeachImage(ProductTypeEnum.IM);
            // 下架所有未更新数据
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct::getIsEurope, ProductTypeEnum.IM.getCode())
                    .eq(StoreProduct::getUpdateFlag, false)
                    .eq(StoreProduct :: getIsShow, true)
                    .eq(StoreProduct :: getIsDel, false)
                    .set(StoreProduct::getIsShow, false)
                    .set(StoreProduct::getStock, 0)
                    .set(StoreProduct::getLastPushTime, new Date())
                    .set(StoreProduct::getIsTusou, false)
                    );
            // 下架所有sku库存
            storeProductService.downloadSku(ProductTypeEnum.IM.getCode());

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return false;
    }

    /**
     * 商品构建处理
     * @Description:  
     * @author daigb 
     * @param @param products
     * @return void
     * @throws
     */
    private void buildProduct(List<ImProduct> products) {
        try {
            for (ImProduct product : products) {
                List<ImProductSku> skus = imProductSkuService.list(Wrappers.<ImProductSku>lambdaQuery()
                        .eq(ImProductSku :: getProductId, product.getProductId())
                        .isNotNull(ImProductSku::getSize)
                        .gt(ImProductSku :: getQty, 0)
                        .eq(ImProductSku :: getStatus, 1)
                        );
                if (CollectionUtils.isEmpty(skus)) {
                    continue;
                }
                // 库存计算
                int stock = 0;
                for (ImProductSku sku : skus) {
                    stock += sku.getQty();
                }

                // 构建实体
                StoreProductCrmebRequest storeProductCrmebRequest = sourceImProductUtil.buildImProduct(product, skus);
                // 数据保存
                StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode(), storeProductCrmebRequest.getSuppliersId(), storeProductCrmebRequest.getKeyword());
                boolean crmebUpdate = true;
                if (null != storeProduct && null != storeProduct.getLastPushTime()) {
                    long time = (System.currentTimeMillis() - storeProduct.getLastPushTime().getTime()) / 1000 / 60;
                    if (60 > time) {
                        log.info("--------------- 该商品: {} 上次IM更新时间: {} 小于一小时, 不进行更新 ---------------", storeProductCrmebRequest.getBarCode(), storeProduct.getLastPushTime());
                        crmebUpdate = false;
                        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                                .eq(StoreProduct::getId, storeProduct.getId())
                                .set(StoreProduct::getUpdateFlag, true)
                                );
                    }
                }
                if (crmebUpdate) {
                    storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getLocalizedMessage());
        }
    }

    /**
     * 推送自有商品到im
     */
    @Override
    public void pushOutImProduct() {
        try {
//            ChannelMerchant channelMerchant = channelMerchantService.getOne(Wrappers.<ChannelMerchant>lambdaQuery()
//                    .eq(ChannelMerchant :: getChannelName, "IM")
//                    );
//            JSONArray suppliers = JSONArray.parseArray(channelMerchant.getSuppliersIds());
            JSONArray suppliers = JSONArray.parseArray("[174]");
            
            int count = storeProductService.count(Wrappers.<StoreProduct>lambdaQuery()
                    .in(!suppliers.isEmpty(), StoreProduct :: getSuppliersId, suppliers)
                    .eq(StoreProduct :: getIsDel, false)
                    .in(StoreProduct :: getTempId, Arrays.asList(1, 11))
                    .ge(StoreProduct :: getLastPushTime, DateUtil.parse("2022-04-22").toJdkDate())
//                    .eq(StoreProduct :: getIsShow, true)
                    .notIn(StoreProduct :: getBrandId, 5429)
                    );
            // 商品推送
            int pageNo = 1;
            int pageSize = 30;
            int maxPage = (count + pageSize - 1) / pageSize;
            log.info("--------------- 开始分页查询IM商品源数据, 本次推送总条数为: {} ---------------", count);

            // 获取当前批次
            String batchId = imProductUtil.getImPushProductBatch();
            log.info("--------------- 当前批次号: {} ---------------", batchId);

            int total = 0;
            long millis = System.currentTimeMillis();
            while (pageNo <= maxPage) {
                try {
                    PageHelper.startPage(pageNo, pageSize);
                    List<StoreProduct> storeProducts = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                            .in(!suppliers.isEmpty(), StoreProduct :: getSuppliersId, suppliers)
                            .eq(StoreProduct :: getIsDel, false)
                            .in(StoreProduct :: getTempId, Arrays.asList(1, 11))
                            .ge(StoreProduct :: getLastPushTime, DateUtil.parse("2022-04-22").toJdkDate())
//                            .eq(StoreProduct :: getIsShow, true)
                            .notIn(StoreProduct :: getBrandId, 5429)
                            );
                    PageInfo<StoreProduct> pageInfo = PageInfo.of(storeProducts);
                    List<StoreProduct> products = pageInfo.getList();
                    total += pushProduct(products, batchId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                log.info("--------------- 推送本地商品到IM, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int)((System.currentTimeMillis() - millis) / 1000 / 60));
                pageNo++;
            }
            
            // 结束当前批次
            imProductUtil.endImPushProductBatch(batchId, total);

            log.info("--------------- 推送本地商品到IM完成! ---------------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private Integer pushProduct(List<StoreProduct> products, String batchId) throws Exception {
        // 查询description
        List<StoreProductDescription> descriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
                .select(StoreProductDescription::getProductId, StoreProductDescription::getDescription)
                .in(StoreProductDescription::getProductId, products.stream().map(StoreProduct::getId).collect(Collectors.toList()))
        );
        
        Map<Integer, String> descriptionMap = new HashMap<>();
        for(StoreProductDescription desc : descriptions) {
        	if(null == descriptionMap.get(desc.getProductId()) && StringUtils.isNotBlank(desc.getDescription())) {
        		descriptionMap.put(desc.getProductId(), desc.getDescription());
        	}
        }
        
        List<ImProductPushDTO> imProducts = new ArrayList<>();
        for(StoreProduct product : products) {
            CategoryMatch category3 = categoryMatchService.getById(product.getCateId());
            CategoryMatch category2 = null != category3 ? categoryMatchService.getById(category3.getPid()) : null;
            CategoryMatch category1 = null != category2 ? categoryMatchService.getById(category2.getPid()) : null;
            try {
                List<StoreProductAttrValue> values = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                        .eq(StoreProductAttrValue :: getProductId, product.getId())
                        );
                if (StringUtils.isNotBlank(descriptionMap.get(product.getId()))) {
                    product.setStoreInfo(descriptionMap.get(product.getId()));
                }
                imProducts.addAll(imProductUtil.createImGoods(product, values, category1, category2, category3));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int total = 0;
        if(CollectionUtil.isNotEmpty(imProducts)) {
        	imProductUtil.batchUpdateImGoods(imProducts, batchId);
        	total = imProducts.size();
        }
        
        return total;
    }

}
